import json
import uuid

import requests
from flask import Blueprint, request, jsonify


from config import APPID, APPSecret
from extension import db
from models.models import UserModel
bp=Blueprint('minisoft',__name__,url_prefix='/minisoft')

#前端会发起登录请求拿到code发给后端去请求openid
def request_openid_from_wx(code):
    req_params = {
        'appid': APPID,
        'secret': APPSecret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    wx_login_api = 'https://api.weixin.qq.com/sns/jscode2session'
    try:
        response_data = requests.get(wx_login_api, params=req_params)
        response_data.raise_for_status()  # 如果请求不成功，会引发 HTTPError
        return response_data.json()
    except requests.RequestException as e:
        print(e)
        # logger.error(f"Failed to request openid from WeChat: {e}")
        return None
def get_or_create_user(userinfo):
    openid=userinfo["openid"]
    username=userinfo["name"]
    user_img=userinfo["avatar"]
    user = UserModel.query.filter(UserModel.OpenID == openid).first()
    if user is None:
        user = UserModel(OpenID=openid,username=username,user_img=user_img)
        db.session.add(user)
        db.session.commit()
        # logger.info("User not found, created new user in database")
    return user.to_dict()


@bp.route('/get_openid', methods=['POST'])
def get_openid():
    try:
        # wxlogincode = json.loads(logincode)调试形参可传，网络请求只能通过协议传参
        wxlogincode = json.loads(request.get_data().decode('utf-8'))
        code = wxlogincode.get('code')
        if code is None:
            # logger.error("No 'code' in the request data")
            return jsonify({"error": "Invalid request data, 'code' is missing"}), 400
    except json.JSONDecodeError as e:
        # logger.error(f"Failed to decode JSON data: {e}")

        return jsonify({"error": "Invalid JSON data"}), 400
    data = request_openid_from_wx(code)
    if data is None:
        return jsonify({"error": "openid请求失败！"}), 500
    openid = data.get('openid')
    session_key = data.get('session_key')

    # 这里要分开，获取openid就获取openid不搞乱七八糟的，把存储用户剥离出去
    # 所以，以下存储部分应删除，这里只返回sessionid和一个用户是否存在的标志位
    if openid and session_key:
        return openid
    else:
        return None

# 应该是上面做好判断如果库有就别执行后面了
@bp.route('/storeuserinfo', methods=['POST'])
def storeuserinfo():
    # 拿到用户名头像openid
    data = json.loads(request.get_data().decode('utf-8'))
    # print(data)
    user_info = get_or_create_user(data)
    # print(user_info)
    return jsonify(user_info)

